﻿using NLog;
using System;
using System.IO;
using System.Text;

namespace Com.Lancetinc.Evs.Helpers
{
    public static class FileUtil
    {
        /// <summary>
        /// 确保文件对应的文件夹存在
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        public static bool EnsureDirectoryExists(string file)
        {
            return DirUtil.EnsureDirectoryExists(new FileInfo(file).DirectoryName);
        }

        public static bool Delete(string file)
        {
            if (!File.Exists(file))
                return false;
            try
            {
                File.Delete(file);
                return true;
            }
            catch (Exception e)
            {
                LogManager.GetCurrentClassLogger().Error(e);
            }

            return false;
        }

        /// <summary>
        /// 写入/替换文本
        /// </summary>
        /// <param name="path">文本路径</param>
        /// <param name="contents">文本内容</param>
        /// <param name="encoding"></param>
        public static void WriteAllText(string path, string contents, Encoding encoding = null)
        {
            encoding ??= Encoding.UTF8;

            var tempFile = path + ".tmp";
            Delete(tempFile); // 临时文件存在的话先删除
            try
            {
                File.WriteAllText(tempFile, contents, encoding);
                File.Copy(tempFile, path, true);
            }
            finally
            {
                Delete(tempFile);
            }
        }
    }
}